package org.streets.eis.ext.analysis.internal.impl;

import java.util.List;
import org.streets.database.ExecMode;
import org.streets.database.Limits;
import org.streets.database.PV;
import org.streets.database.SQLConnection;
import org.streets.eis.ext.analysis.entities.QueryStruct;
import org.streets.eis.ext.analysis.services.QueryDAO;



public class QueryDAOImpl implements QueryDAO {
    
	private final SQLConnection _connection;
	
	public QueryDAOImpl(SQLConnection connection) {
		this._connection = connection;
	}

	private void deleteQuerySub(String queryId){
		_connection.execute("delete eis_query_where where query_id=:queryid", PV.nv("queryid", queryId));
		_connection.execute("delete eis_query_disp where query_id=:queryid", PV.nv("queryid", queryId));
		_connection.execute("delete eis_query_order where query_id=:queryid", PV.nv("queryid", queryId));
	}

	public void delete(QueryStruct query) {
		_connection.execute(query, ExecMode.DELETE);
		deleteQuerySub(query.getId());
	}
	
	public List<QueryStruct> findQueries() {
		return _connection.query("select * from eis_query", QueryStruct.class, Limits.none());
	}

	 
	public void insert(QueryStruct query){
		_connection.execute(query, ExecMode.CREATE);
		_connection.execute(query.getWhereFields(), ExecMode.CREATE);
		_connection.execute(query.getDisplayFields(), ExecMode.CREATE);
		_connection.execute(query.getOrderFields(),ExecMode.CREATE);
	}

	public void update(QueryStruct query) {
		_connection.execute(query, ExecMode.UPDATE);
		deleteQuerySub(query.getId());
		_connection.execute(query.getWhereFields(), ExecMode.CREATE);
		_connection.execute(query.getDisplayFields(), ExecMode.CREATE);
		_connection.execute(query.getOrderFields(),ExecMode.CREATE);
	}
	
 
	 
}
